import { PageTableProps } from '@/layout/table-layout.vue';
import { shallowRef } from 'vue';
import { hookResult } from './bindResult';
import { TSimpleFormResult } from './useForm';
import { TPaginationTableResult } from './usePaginationTable';

// eslint-disable-next-line import/prefer-default-export
export function usePageTable<
  SearchParams extends Record<string, any>,
  DataType = any
>(props: PageTableProps<SearchParams>) {
  const pageTableRef = shallowRef();

  const setRef = (pageTable: any) => {
    // console.log('setref', pageTable);
    pageTableRef.value = pageTable;
  };

  const table = (): TPaginationTableResult<DataType> | null => {
    if (!pageTableRef.value) {
      // console.error('pageTableRef 为null');
      return null;
    }
    return pageTableRef.value.getTable();
  };

  const form = (): TSimpleFormResult<SearchParams> | null => {
    if (!pageTableRef.value) {
      // console.error('pageTableRef 为null');
      return null;
    }

    return pageTableRef.value.getForm();
  };

  const reload = () => {
    table()?.reload();
  };

  const reset = () => {
    form()?.backToInit();
  };

  return hookResult(
    {
      reload,
      reset,
      get form() {
        return form();
      },
      get table() {
        return table();
      },
    },
    {
      ...props,
      ref: setRef,
    }
  );
}
